package com.alander.nexusgo.im.netty;

import com.alander.nexusgo.im.netty.codec.ImMessageDecoder;
import com.alander.nexusgo.im.netty.codec.ImMessageEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

/**
 * Netty服务器启动器
 */
@Component
public class NettyServerStarter {

    private static final Logger LOGGER = LoggerFactory.getLogger(NettyServerStarter.class);

    @Value("${im.tcp.port:9100}")
    private int tcpPort;

    @Value("${im.ws.port:9101}")
    private int wsPort;

    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workerGroup;

    @PostConstruct
    public void start() throws UnknownHostException {
        // 启动TCP服务器
        startTcpServer();

        // 启动WebSocket服务器
        startWsServer();
    }

    private void startTcpServer() {
        new Thread(() -> {
            try {
                bossGroup = new NioEventLoopGroup(1);
                workerGroup = new NioEventLoopGroup();

                ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                // 添加TCP消息处理器
                                ch.pipeline().addLast(new IdleStateHandler(300, 0, 0, TimeUnit.SECONDS)); // 5分钟没有读取数据则触发
                                ch.pipeline().addLast(new ImMessageDecoder()); // 消息解码器
                                ch.pipeline().addLast(new ImMessageEncoder()); // 消息编码器
                                ch.pipeline().addLast(new ImLoginHandler()); // 登录处理器
                                ch.pipeline().addLast(new PrivateChatHandler()); // 私聊处理器
                                ch.pipeline().addLast(new ChatRoomHandler()); // 聊天室处理器
                                LOGGER.info("TCP客户端连接: {}", ch.remoteAddress());
                            }
                        });

                ChannelFuture channelFuture = serverBootstrap.bind(tcpPort).sync();
                LOGGER.info("TCP服务器启动成功，监听端口: {}", tcpPort);
                channelFuture.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                LOGGER.error("TCP服务器启动失败", e);
            }
        }, "tcp-server-thread").start();
    }

    private void startWsServer() {
        new Thread(() -> {
            try {
                // 如果需要WebSocket服务器，可以在这里实现
                LOGGER.info("WebSocket服务器端口: {}", wsPort);
            } catch (Exception e) {
                LOGGER.error("WebSocket服务器启动失败", e);
            }
        }, "ws-server-thread").start();
    }

    @PreDestroy
    public void stop() {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        LOGGER.info("Netty服务器已关闭");
    }
}